package com.customization.unionpay.market.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author sjm
 * @description excel数据工具类
 */
public class ExcelUtils {

    /**
     * 获取row下标
     * @param headerRow
     * @param columnName
     * @return
     */
    public static int findColumnIndex(Row headerRow, String columnName) {
        for (Cell cell : headerRow) {
            if (cell.getCellType() == CellType.STRING && columnName.equals(cell.getStringCellValue())) {
                return cell.getColumnIndex();
            }
        }
        return -1; // 未找到列名
    }

    /**
     * 获取Cell的值
     * @param cell
     * @return
     */
    public static String getCellValue(Cell cell){
        String value = null;
        if(cell != null){
            // 根据单元格类型获取数据
            switch (cell.getCellType()) {
                case STRING:
                    value = cell.getStringCellValue();
                    break;
                case NUMERIC:
                    if(DateUtil.isCellDateFormatted(cell)){
                        Date date = cell.getDateCellValue();
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        value = dateFormat.format(date);
                    }else {
                        value = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                case BOOLEAN:
                    boolean booleanCellValue = cell.getBooleanCellValue();
                    if (booleanCellValue) {
                        value = "0";
                    } else {
                        value = "1";
                    }
                    break;
                case FORMULA:
                    value = cell.getCellFormula();
                    break;
                default:
                    break;
            }
            if(value != null){
                boolean isAllZerosAfterDecimal = value.matches(".*\\.0+$");
                if(isAllZerosAfterDecimal){
                    value = value.split("\\.")[0];
                }
            }
        }
        return value;
    }
}
